package com.southpark.framework.control.proxies
{
	import com.southpark.framework.control.commands.CommandFault;
	import com.southpark.framework.control.responders.IResponder;
	import com.southpark.framework.services.IService;
	
	import flash.utils.getQualifiedClassName;
	
	import mx.rpc.Fault;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	
	public class AbstractProxy implements IProxy,IDeserializer
	{
		static protected var isFakeServerMode:Boolean;
		
		private var responder:IResponder;
		private var deserializer:IDeserializer;
		private var serviceClass:Class;
		protected var backendMethod:String;
		
		
		public function AbstractProxy(responder:IResponder,serviceClass:Class,fakeServiceClass:Class=null)
		{
			this.responder = responder;
			this.serviceClass = (isFakeServerMode && fakeServiceClass) ? fakeServiceClass : serviceClass;
		}
		
		protected function callService(deserializer:IDeserializer,backendMethod:String=null,parameters:Array=null):void
		{						
			this.deserializer = deserializer;
			this.backendMethod = backendMethod;
			
			var service:IService = IService(new serviceClass(this));
            service.execute(backendMethod,parameters);
		}
		
		
		
		/**
		 * IProxy
		 */
		public function onServiceSuccess(event:ResultEvent):void
		{
			onProxySuccess(event.result);
		}
		
		public function onServiceFault(event:FaultEvent):void
		{
			onProxyFault(event.fault);
		}
		
		
		/**
		 * IDeserializer
		 */
		public function manageSuccess(data:Object):Object
		{
			 /**
			 * Should deserialize the data received from the server and then return it
			 */
			 return null;
		}
		
		public function manageFault(faultCode:String):String
		{
			 /**
			 * Should return the faultCode
			 */
			 return null;
		}
		
		
		/**
		 * 
		 */
		private function onProxySuccess(result:Object):void
		{
			responder.onSuccess(deserializer.manageSuccess(result));
			responder = null;
		}
		
		private function onProxyFault(fault:Fault):void
		{
			var commandFault:CommandFault = new CommandFault();
			commandFault.proxyClassName = getQualifiedClassName(this);
			commandFault.backendMethod = backendMethod;
			commandFault.fault = fault;
			commandFault.faultCode = deserializer.manageFault(fault.faultCode);
			
			responder.onFault(commandFault);
			responder = null;
		}

	}
}